package com.zxl.grocery.modular.crawler.scheduled;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxl.grocery.modular.crawler.entity.CrawlerConfig;
import com.zxl.grocery.modular.crawler.pipeline.FunnyPipeline;
import com.zxl.grocery.modular.crawler.processor.DuanZiGeProcessor;
import com.zxl.grocery.modular.crawler.service.CrawlerConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Spider;

import java.util.List;


/**
 * info:笑话定时任务
 * Created by Lzx on 2017/7/12.
 */
@Component("FunnyScheduled")
public class FunnyScheduled {

    @Autowired
    private FunnyPipeline funnyPipeline;
    @Autowired
    private CrawlerConfigService crawlerConfigService;

    /**
     * 段子哥
     */
    ////[秒] [分] [小时] [日] [月] [周] [年]
//    @Scheduled(cron = "0 0/30 0 * * ? ")//从0点开始,每4个小时执行一次
    public void duanZiGeScheduled() {
        QueryWrapper<CrawlerConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper = queryWrapper.eq("code", "DuanZiGeScheduled");
        List<CrawlerConfig> crawlerConfigs = crawlerConfigService.list(queryWrapper);
        if (crawlerConfigs.size() > 0) {
            for (int i = 0; i < crawlerConfigs.size(); i++) {
                if (crawlerConfigs.get(i).getContent().equals("1")) {
                    QueryWrapper<CrawlerConfig> configQueryWrapper = new QueryWrapper<>();
                    configQueryWrapper = configQueryWrapper.eq("code", "DuanZiGeScheduledNum");
                    List<CrawlerConfig> crawlerConfigList = crawlerConfigService.list(configQueryWrapper);
                    if (crawlerConfigList.size() > 0) {
                        for (int j = 0; j < crawlerConfigList.size(); j++) {
                            if (StringUtils.isNotEmpty(crawlerConfigList.get(j).getContent())) {
                                System.out.println("----开始段子哥定时任务");
                                Spider spider = Spider.create(new DuanZiGeProcessor());
                                int num = Integer.valueOf(crawlerConfigList.get(j).getContent()) + 1;
                                System.out.println(crawlerConfigList.get(j).getContent());
                                spider.addUrl("http://www.duanzige.cn/list-2-" + num + ".html");
                                spider.addPipeline(funnyPipeline);
                                spider.thread(5);
                                spider.setExitWhenComplete(true);
                                spider.start();
                                spider.stop();
                                crawlerConfigList.get(j).setContent(num + "");
                                crawlerConfigService.saveOrUpdate(crawlerConfigList.get(j));
                            }
                        }
                    }
                }
            }
        }
    }
}
